import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { BASE_URL, JWT_LS } from '../constants'

export const getTokenFromLocalStorage = () => {
    return localStorage.getItem(JWT_LS)
}

export const usersApi = createApi({
    reducerPath: 'usersApi',
    baseQuery: fetchBaseQuery(
        { baseUrl: `${BASE_URL}/users`, headers: {Authorization: `Bearer ${getTokenFromLocalStorage()}`}  }),
    endpoints: (builder) => ({
        getUser: builder.query<any, void>({
            query: () => 'me',
        }),
        patchUser: builder.mutation({
            query: (user) => ({
                method: 'PATCH',
                body: user,
                url: 'me'
            }),
        }),
    }),
})

export const {
    useGetUserQuery,
    usePatchUserMutation
} = usersApi
